package com.zues.samples.web;

import java.io.File;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

	@RequestMapping(value = "upload", method = RequestMethod.GET)
	private String toUpload (){
		return "common/upload";
	}
	
	
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session,
			ModelMap model) {
		String path = session.getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		System.out.println(path);
		File targetFile = new File(path,fileName);
		if(!targetFile.exists()){
			targetFile.mkdirs();
		}
		
		//保存
		try{
			file.transferTo(targetFile);
		}catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("message", "Upload successfully");
		return "common/upload";
	}
}
